#!/usr/bin/env node

'use strict';

let argv = require('minimist')(process.argv.slice(2));
const fs = require('fs');
const path = require('path');
const spawn = require('child_process').spawn;
const childpros = require('child_process');
const logger = require('tracer').colorConsole();

let arg = argv._[0];

process.env.INIT_CWD = process.cwd();
let local = process.cwd();

if (arg == "install") {
  fs.readFile(path.join(process.env.INIT_CWD, 'package.json'), function (err, bytesRead) {
    if (err) throw err;
    var data = JSON.parse(bytesRead);
    // console.log(data);
    logger.log(data["parent"])
    // readParent(data["parent"]["path"])
    let models = data["models"]
    for (let value in models) {
      logger.log(models[value]);
      readModels(models[value]);
    }
  });
}

function readParent(ppath) {
  let realpth = path.resolve(local, ppath, "package.json");

  logger.log(realpth);

  fs.readFile(realpth, function (err, bytesRead) {
    if (err) throw err;
    var data = JSON.parse(bytesRead);
    logger.log(data);

    let targ = 'npm install ' + ppath;


    childpros.exec(targ, function (err, stdout, stderr) {
      logger.log(stdout);
      logger.log("安装完成...")
    });
    // const insta = spawn("npm",['install',ppath])
    // insta.stdout.on('data', function (data) {
    //     logger.log( data);
    // });
    logger.log("please wait 代码正在分析安装中...")
  });
}

function readLoacl(localPath) {

}

function readModels(mpath) {
  let realpth = path.resolve(local, mpath, "package.json");

  logger.log(realpth);

  fs.readFile(realpth, function (err, bytesRead) {
    if (err) throw err;
    var data = JSON.parse(bytesRead);
    logger.log(data);
    let targ = 'npm install ' + mpath;

    childpros.exec(targ, function (err, stdout, stderr) {
      logger.log(stdout);
      logger.log("安装完成...")
    });
    // const insta = spawn("npm",['install',ppath])
    // insta.stdout.on('data', function (data) {
    //     logger.log( data);
    // });
    logger.log(mpath + "mpath 代码正在分析安装中...")
  });

}

function analysisParent() {

}

function analysisModels() {

}

function installParent() {

}

function installmodels() {

}


//TODO 分析 项目中的 parent 属性，定位读取parent项目的package.json
//TODO 分析 项目中的 models 属性, 定位读取各个子项目的package.json

//TODO 分析父级项目与当前项目的属性相关性
//TODO 分析子模块中的依赖是否跟目前版本中的存在相关性

//TODO 对所有的一级依赖进行汇总，并merge，尝试开启多线程npm install package@version

